//
//  AFHTTPRequestOperationManager+KLRACSupport.m
//  KoalaUtilKit
//
//  Created by Tommy on 15/1/8.
//  Copyright (c) 2015年 Koala Team. All rights reserved.
//

#import "AFHTTPRequestOperationManager+KLRACSupport.h"
#import "AFHTTPRequestOperation+KLRACSupport.h"

@implementation AFHTTPRequestOperationManager (KLRACSupport)

- (RACSignal *)klrac_enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)requestOperation {
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[requestOperation klrac_overrideHTTPProgressBlock] subscribe:subscriber];
        [[requestOperation rac_overrideHTTPCompletionBlock] subscribe:subscriber];
        [self.operationQueue addOperation:requestOperation];
        return [RACDisposable disposableWithBlock:^{
            [requestOperation cancel];
        }];
    }];
}

- (RACSignal *)klrac_enqueueBatchOfHTTPRequestOperations:(NSArray *)requestOperations {
    return nil;
}

- (RACSignal *)klrac_GET:(NSString *)path parameters:(id)parameters {
    return [[self klrac_requestPath:path parameters:parameters method:@"GET"]
            setNameWithFormat:@"%@ -klrac_GET: %@, parameters: %@", self.class, path, parameters];
}

- (RACSignal *)klrac_POST:(NSString *)path parameters:(id)parameters {
    return [[self klrac_requestPath:path parameters:parameters method:@"POST"]
            setNameWithFormat:@"%@ -klrac_POST: %@, parameters: %@", self.class, path, parameters];
}

- (RACSignal *)klrac_PUT:(NSString *)path parameters:(id)parameters {
    return [[self klrac_requestPath:path parameters:parameters method:@"PUT"]
            setNameWithFormat:@"%@ -klrac_PUT: %@, parameters: %@", self.class, path, parameters];
}

- (RACSignal *)klrac_DELETE:(NSString *)path parameters:(id)parameters {
    return [[self klrac_requestPath:path parameters:parameters method:@"DELETE"]
            setNameWithFormat:@"%@ -klrac_DELETE: %@, parameters: %@", self.class, path, parameters];
}

- (RACSignal *)klrac_PATCH:(NSString *)path parameters:(id)parameters {
    return [[self klrac_requestPath:path parameters:parameters method:@"PATCH"]
            setNameWithFormat:@"%@ -klrac_PATCH: %@, parameters: %@", self.class, path, parameters];
}

- (RACSignal *)klrac_requestPath:(NSString *)path parameters:(id)parameters method:(NSString *)method {
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        NSURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
        
        AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
        [[operation klrac_overrideHTTPProgressBlock] subscribe:subscriber];
        [[operation rac_overrideHTTPCompletionBlock] subscribe:subscriber];
        [self.operationQueue addOperation:operation];
        return [RACDisposable disposableWithBlock:^{
            [operation cancel];
        }];
    }];
}
- (RACSignal *)klrac_upload:(NSString *)path parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block{
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        
        AFHTTPRequestOperation* operation = [self POST:path parameters:parameters constructingBodyWithBlock:block success:nil failure:nil];
        [[operation klrac_overrideHTTPProgressBlock] subscribe:subscriber];
        [[operation rac_overrideHTTPCompletionBlock] subscribe:subscriber];
        [self.operationQueue addOperation:operation];
        return [RACDisposable disposableWithBlock:^{
            [operation cancel];
        }];
    }];
}

- (RACSignal *)klrac_download:(NSString *)path parameters:(id)parameters filePath:(NSString*)filePath{
    return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];        
        operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
        [[operation klrac_overrideHTTPProgressBlock] subscribe:subscriber];
        [[operation rac_overrideHTTPCompletionBlock] subscribe:subscriber];
        [self.operationQueue addOperation:operation];
        return [RACDisposable disposableWithBlock:^{
            [operation cancel];
        }];
    }];
    
}




#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
#pragma mark - Upload Request (iOS 7 only)

//上传（iOS7专用）
- (void)methodUploadFor7:(NSString*)path toFilePath:(NSString*)filePath{
    
    AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    //发送上传请求
    NSURLSessionUploadTask *uploadTask = [sessionManager uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:filePath] progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            
            //请求失败
            NSLog(@"Error: %@", error);
            
        } else {
            
            //请求成功
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    
    //开始上传
    [uploadTask resume];
}

#pragma mark - Download Request (iOS 7 only)

//下载（iOS7专用）
- (void)methodDownloadFor7:(NSString*)path toFilePath:(NSString*)filePath
{

    
    //创建请求（iOS7专用）
    AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    //添加请求接口
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    //发送下载请求
    NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        //设置存放文件的位置（此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径，请自行搜索相关资料）
//        NSURL *filePath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
        
        return [[NSURL fileURLWithPath:filePath] URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        //下载完成
        NSLog(@"Finish and Download to: %@", filePath);
    }];
    
    //开始下载
    [downloadTask resume];
}

#endif //ios7.0



@end
